<!-- 选择配送区域 -->
<template>
  <el-dialog title="配送区域" v-model="editVisible" width="50%" :close-on-click-modal="closeOnClickModal" draggable @closed="closedFormDialog">
    <el-form label-width="150px">
      <el-row :gutter="10">
        <el-col :span="20">
          <el-form-item label="选择可配送区域：">
            <!-- 多加一个div的作用：防止全选和内容在同一行 -->
            <div>
              <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
              <el-checkbox-group v-model="checkedProvinces" @change="handleCheckedCitiesChange">
                <el-checkbox v-for="item in provinceSelectList" :label="item.id" :value="item.id" :key="item.id">{{ item.name }}</el-checkbox>
              </el-checkbox-group>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" v-if="!isDisabledbtn" @click="submitSelectProvince">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import type { CheckboxValueType } from "element-plus";
import type { IRegion } from "@/types/redPacketMallManage/region";

interface Props {
  provinceSelectList: Array<IRegion>;
}
const { provinceSelectList } = defineProps<Props>();
const emit = defineEmits<{
  submitSelectProvince: [];
}>();

const editVisible = defineModel<boolean>("editVisible", { required: true });
const checkAll = defineModel<boolean>("checkAll", { required: true });
const checkedProvinces = defineModel<Array<number>>("checkedProvinces", { required: true });

const closeOnClickModal = ref(false);
const isDisabledbtn = ref(false);

/* 设置不确定状态*/
const isIndeterminate = computed(() => {
  return checkedProvinces.value.length > 0 && checkedProvinces.value.length < provinceSelectList.length;
});

// 关闭模态框
function closedFormDialog() {
  editVisible.value = false;
  checkedProvinces.value = [];
}

/* 全选 */
function handleCheckAllChange(val: CheckboxValueType) {
  checkedProvinces.value = val ? provinceSelectList.map(item => item.id) : [];
}

/* 点击选择省 */
function handleCheckedCitiesChange(value: CheckboxValueType[]) {
  handleCheckAll(value.length, provinceSelectList.length);
}
/* 修改全选与部分选 的样式 */
function handleCheckAll(checkedCount: number, selectListLength: number) {
  checkAll.value = checkedCount === selectListLength;
}

/* 确定选择省 */
function submitSelectProvince() {
  editVisible.value = false;
  emit("submitSelectProvince");
}
</script>

<style lang="scss" scoped>
/* 修改select的盒模型 */
.el-select {
  display: block;
}
</style>
